<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>CORS</title>
  </head>

  <body>
    <h3 id="data">数据未加载...</h3>
    <button id="btn">发起AJAX请求</button>

    <!-- <form action="./server.php" method="POST">
        用户名：<input type="text" id="ipUsername" name="username"><br>
        密码：<input type="password" id="ipPassword" name="pwd"><br>
        <button>登录</button>
    </form> -->

    <!-- access访问 origin源 block阻断 policy政策/策略 -->
    <!-- cors = cross origin resource share 跨域资源共享 -->

    <script>
      btn.onclick = function (e) {
        xhrRequestInLiveServer();
      };

      function xhrRequestInLiveServer() {
        // 创建一个XHR对象
        const xhr = new XMLHttpRequest();
        /* 
            Access to XMLHttpRequest at 'localhost:3000' from origin 'http://127.0.0.1:5500' 
            一个从5500到3000的XHR访问

            has been blocked by 【CORS policy】: 
            已经被【同源策略】所阻止了：
            CORS policy = Cross Origin Resource Share 跨域资源共享策略，简称【同源策略】

            Cross origin requests are only supported for protocol schemes: 
            跨域请求仅被以下协议计划支持（浏览器发起的跨域访问不受支持）

            http, data, chrome, chrome-extension, chrome-untrusted, https.
            一大堆其它
            */

        xhr.open("GET", "localhost:3000");

        //发送合适的请求头信息
        // xhr.setRequestHeader(
        //     "Content-type",
        //     "application/x-www-form-urlencoded"
        // );

        // 监听【就绪状态变更事件】
        xhr.onload = function () {
          console.log(xhr.responseText);
          data.innerText = xhr.responseText;
        };

        // 发送请求
        xhr.send(null);
        // xhr.send("username=admin&pwd=123456");
        // xhr.send({form: 'username=admin&pwd=123456'});

        console.log("请求发送完毕");
      }
    </script>
  </body>
</html>
